package com.cool.modules.finance.service.category.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONObject;
import com.cool.core.base.BaseServiceImpl;
import com.cool.core.exception.CoolException;
import com.cool.core.util.CoolSecurityUtil;
import com.cool.modules.finance.entity.category.FinanceCategoryEntity;
import com.cool.modules.finance.mapper.category.FinanceCategoryMapper;
import com.cool.modules.finance.service.category.FinanceCategoryService;
import com.cool.modules.finance.service.family.FinanceUserFamilyService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import static com.cool.modules.finance.entity.category.table.FinanceCategoryEntityTableDef.FINANCE_CATEGORY_ENTITY;
import static com.cool.modules.finance.entity.family.table.FinanceFamilyEntityTableDef.FINANCE_FAMILY_ENTITY;

@Service
@RequiredArgsConstructor
public class FinanceCategoryServiceImpl extends BaseServiceImpl<FinanceCategoryMapper, FinanceCategoryEntity> implements FinanceCategoryService {

    final FinanceUserFamilyService userFamilyService;

    @Override
    public Long add(FinanceCategoryEntity entity) {
        if(StringUtil.isBlank(entity.getCategoryCode())){
            entity.setCategoryCode(PinyinUtil.getFirstLetter(entity.getCategoryName(), ""));
        }
        if (null==entity.getFamilyId()){
            Long userId = CoolSecurityUtil.getCurrentUserId();
            Long familyId = userFamilyService.getFamilyIdByUserId(userId);
            if (null==familyId){
                throw new CoolException("当前用户没有绑定家庭，请先绑定家庭再试");
            }
            entity.setFamilyId(familyId);
        }
        if (null==entity.getHotOrder()){
            entity.setHotOrder(0);
        }

        return super.add(entity);
    }

    @Override
    public Object page(JSONObject requestParams, Page<FinanceCategoryEntity> page, QueryWrapper queryWrapper) {
        CoolSecurityUtil.getAdminUserInfo(requestParams);
        queryWrapper.select(FINANCE_CATEGORY_ENTITY.ALL_COLUMNS,
                FINANCE_FAMILY_ENTITY.NAME.as("familyName")
        );
        queryWrapper.from(FINANCE_CATEGORY_ENTITY).leftJoin(FINANCE_FAMILY_ENTITY)
                .on(FINANCE_CATEGORY_ENTITY.FAMILY_ID.eq(FINANCE_FAMILY_ENTITY.ID));
        queryWrapper.orderBy(FinanceCategoryEntity::getHotOrder, false);
        return super.page(requestParams, page, queryWrapper);
    }
}
